/*
 *  @Title FreemarkerHelper.java
 *  @Package： com.phoenix.core.freemarker
 *  Copyright (c) 2017 by 江苏深南互联网金融信息服务有限公司  All right reserved
 */
package com.phoenix.core.freemarker;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import com.phoenix.core.logger.SimpleLogger;
import com.phoenix.exception.NestedBusinessException;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;


/**
 *  @ClassName FreemarkerHelper
 *  @Description 工具类
 *  @author yijun
 *  @version 1.0
 *  @date 2017年6月26日
 */
public class FreemarkerHelper {

	SimpleLogger logger = SimpleLogger.getLogger(this.getClass());

	static class SingletonHolder {
		static FreemarkerHelper instance = new FreemarkerHelper();
	}

	public static FreemarkerHelper getInstance() {
		return SingletonHolder.instance;
	}

	Configuration config = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);

	private FreemarkerHelper() {
	}

	public String getProcessContent(String baseDir, String tempName, Map<String, Object> model) {
		Template pt = loadTemplate(baseDir, tempName);
		if (pt == null)
			throw new NestedBusinessException("模板未找到！");
		StringWriter result = new StringWriter();
		try {

			pt.process(model, result);
		} catch (TemplateException e) {
			logger.error("process freemarker template TemplateException", e);
		} catch (IOException e) {
			logger.error("process freemarker template IOException", e);
		}
		return result.toString();
	}

	private Template loadTemplate(String tempDir, String name) {
		try {
			String path = Thread.currentThread().getContextClassLoader().getResource("").getFile();
			if (path.indexOf(":") > 0)
				path = path.substring(path.indexOf("/") + 1, path.length());
			path = new StringBuffer(path).append(tempDir).append(File.separator).toString();
			config.setDirectoryForTemplateLoading(new File(path));
			config.setNumberFormat("###############");
			config.setDefaultEncoding("UTF-8");
			return config.getTemplate(name);
		} catch (Exception e) {
			logger.error("load freemarker template exception", e);
		}
		return null;
	}

	/**
	 * 解析字符串模板
	 * @param temp
	 * @param tempName
	 * @param model
	 * @return
	 */
	public String getContentByStr(String tempStr,String tempName, Map<String, Object> model) {
		StringTemplateLoader stringLoader = new StringTemplateLoader();
		stringLoader.putTemplate(tempName, tempStr);
		config.setTemplateLoader(stringLoader);
		try (StringWriter writer = new StringWriter()) {
			Template template = config.getTemplate(tempName, "utf-8");
			template.process(model, writer);
			return writer.toString();
		} catch (TemplateException | IOException e) {
			logger.error("load freemarker template exception", e);
		}
		return null;

	}
}
